package com.huawei.crm.sample.application.product;

import com.huawei.crm.sample.application.product.converter.ProductDTOConverter;
import com.huawei.crm.sample.application.product.dto.ProductDTO;
import com.huawei.crm.sample.application.product.validator.ProductValidator;
import com.huawei.crm.sample.domain.product.factory.ProductFactory;
import com.huawei.crm.sample.domain.product.model.aggragate.Product;
import com.huawei.crm.sample.domain.product.repository.ProductRepository;
import com.huawei.crm.sample.domain.product.service.ProductDomainService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ProductUseCaseImpl implements ProductUseCase {
    private final ProductRepository productRepository;
    private final ProductDomainService productDomainService;
    private final ProductDTOConverter productDTOConverter;

    @Autowired
    public ProductUseCaseImpl(ProductRepository productRepository, ProductDomainService productDomainService, ProductDTOConverter productDTOConverter) {
        this.productRepository = productRepository;
        this.productDomainService = productDomainService;
        this.productDTOConverter = productDTOConverter;
    }

    @Override
    public ProductDTO createProduct(ProductDTO productDTO) {
        ProductValidator.validateForCreate(productDTO);
        Product product = ProductFactory.create(productDTO.getProductId(), productDTO.getName(), productDTO.getStock(), productDTO.getPrice());
        productRepository.save(product);
        return productDTOConverter.toDTO(product);
    }

    @Override
    public ProductDTO getProduct(String productId) {
        Product product = productRepository.findById(productId);
        return productDTOConverter.toDTO(product);
    }

    @Override
    public void decreaseStock(String productId, int quantity) {
        productDomainService.checkAndDecreaseStock(productId, quantity);
    }
} 